﻿using System;
using System.Threading.Tasks;
using System.Windows;
using Autofac;

namespace Phoenix.Extensions.Autofac
{
    public abstract class AutofacPhoenixApplication : PhoenixApplicationHostTarget
    {
        protected override Task<IPhoenixHost> InitialisePhoenix()
        {
            var hostBuilder = new AutofacPhoenixHostBuilder(
                TaskScheduler.FromCurrentSynchronizationContext(), 
                Dispatcher);
            hostBuilder.ConfigureContainer(ConfigureContainer);
            hostBuilder.ContainerReady(container =>
            {
               Container = container;
               ContainerReady();
            });
            ConfigurePhoenixHostBuilder(hostBuilder);
            return hostBuilder.Run(this);
        }

        protected IContainer Container { get; private set; }

        // ReSharper disable EventNeverSubscribedTo.Local
        // ReSharper disable UnusedMember.Local
        // ReSharper disable EventNeverInvoked
        new Uri StartupUri { get; set; }
        new event StartupEventHandler Startup;
        // ReSharper restore EventNeverSubscribedTo.Local
        // ReSharper restore UnusedMember.Local
        // ReSharper restore EventNeverInvoked

        protected override void OnStartup(StartupEventArgs e)
        {
            var handler = Startup;
            if (handler != null) handler(this, e);
            InitialisePhoenix().ContinueWith(t=>Host = t.Result);
        }

        protected abstract void ConfigurePhoenixHostBuilder(IPhoenixHostBuilder hostBuilder);
        protected abstract void ConfigureContainer(ContainerBuilder containerBuilder);
        protected virtual void ContainerReady(){}
    }
}
